<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/24
 * Time: 9:44
 */
namespace App\Service\Api;

use App\Http\Model\Mysql\UserMemberModel;
use App\Http\Model\Mysql\WechatOrderModel;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;

class MemberService extends BaseService
{
    /**
     * 购买会员招募
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function memberShop()
    {
        $user_info      =   request()->post('api_user');
        $user_openid    =   $user_info['openid'];
        $user_id        =   $user_info['user_id'];
        $wechat_config  =   Config::get('wechat');
        $now_time       =   Carbon::now()->timestamp;
        $order_prefix   =   $user_id . $now_time;
        $order_number   =   $order_prefix . (createRandomNumber(24  - strlen($order_prefix)));
        $pre_order['appid']     =   $wechat_config['appid'];
        $pre_order['mch_id']    =   $wechat_config['mch_id'];
        $pre_order['nonce_str'] =   Str::random(32);
        $pre_order['body']      =   '网虹城商品购物';
        $pre_order['detail']    =   '网虹城会员招募';
        $pre_order['attach']    =   '网虹城会员招募';
        $pre_order['total_fee'] =   1;      //$total_fee * 100
        $pre_order['openid']    =   $user_openid;
        $pre_order['spbill_create_ip']  =   request()->getClientIp();
        $pre_order['out_trade_no']      =   $order_number;
        $pre_order['time_start']        =   Carbon::now()->format('YmdHis');
        $pre_order['time_expire']       =   Carbon::parse("+2 hours")->format('YmdHis');
        $pre_order['notify_url']        =   $wechat_config['member_url'];
        $pre_order['trade_type']        =   'JSAPI';
        $pre_order['sign']      =   wechatEncrypt($pre_order, $wechat_config['mch_key']);

        /**
         * 保存预下单记录
         */
        $pre_order_model    =   WechatOrderModel::create($pre_order);

        /**
         * 发起预下单请求
         */
        try {
            $query_client   =   new Client(['verify' => false, 'timeout' => 5]);
            $query_response =   $query_client->post('https://api.mch.weixin.qq.com/pay/unifiedorder', ['body' => xmlEncode($pre_order)]);
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
        }
        $xml_data       =   $query_response->getBody()->getContents();
        $query_result   =   xmlObjectToArray(simplexml_load_string($xml_data, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS | LIBXML_NOERROR));

        /**
         * 预下单请求处理
         */
        if ($query_result['return_code'] == 'FAIL') {
            return [false, $query_result['return_msg']];
        } else {
            $pre_order_model->err_code      =   $query_result['err_code'] ?? '';
            $pre_order_model->err_code_desc =   $query_result['err_code_desc'] ?? '';
            if ($query_result['result_code'] == 'SUCCESS') {
                $pre_order_model->prepay_id = $query_result['prepay_id'] ?? '';
                $pre_order_model->code_url = $query_result['code_url'] ?? '';
                $pre_order_model->save();

                /**
                 * 保存会员购买记录
                 */
                $member_log['user_id']  =   $user_id;
                $member_log['order_no'] =   $order_number;
                $member_log['member_price']=   $pre_order['total_fee'];
                $member_log['is_pay']      =   0;
                $member_log['pay_price']   =   0;
                $member_result  =   UserMemberModel::create($member_log);
                if ($member_result) {
                    $pay_param  =   [
                        'timeStamp' =>  $now_time,
                        'nonceStr'  =>  $pre_order['nonce_str'],
                        'signType'  =>  'MD5',
                        'package'   =>  'prepay_id=' . $pre_order_model->prepay_id,
                        'appId'     =>  $wechat_config['appid']
                    ];
                    $pay_param['paySign']   =   wechatEncrypt($pay_param, $wechat_config['mch_key']);
                    return [true, $pay_param];
                } else {
                    return [false, '购买记录出错'];
                }
            } else {
                $pre_order_model->save();
                return [false, $query_result['err_code_desc'] ?? '请求错误'];
            }
        }
    }
}
